import DataProcessorWorker from '../workers/dataProcessor.worker?worker'
import { ref, onUnmounted } from 'vue'

export function useDataProcessor() {
  const processedData = ref<any[]>([])
  const isLoading = ref(false)
  const error = ref<Error | null>(null)

  let worker: Worker | null = null

  const processData = (rawData: any[]) => {
    isLoading.value = true
    error.value = null

    // 创建 Worker 实例
    worker = new DataProcessorWorker()

    worker.postMessage({
      action: 'processData',
      payload: rawData
    })

    worker.onmessage = (e: MessageEvent) => {
      if (e.data.action === 'processed') {
        processedData.value = e.data.payload
        isLoading.value = false
        worker?.terminate()
      }
    }

    interface WorkerError extends Error {
      filename?: string
      lineno?: number
      colno?: number
    }

    worker.onerror = (event: ErrorEvent) => {
      const err: WorkerError = new Error(event.message)
      err.name = 'WorkerError'
      err.filename = event.filename
      err.lineno = event.lineno
      err.colno = event.colno
      error.value = err
      isLoading.value = false
      worker?.terminate()
    }
  }

  // 组件卸载时清理 Worker
  onUnmounted(() => {
    worker?.terminate()
  })

  return {
    processedData,
    isLoading,
    error,
    processData
  }
}
